package com.huilian.iotbox.data.service.impl;

import com.huilian.iotbox.data.dao.UserCommonDao;
import com.huilian.iotbox.data.dto.UserDto;
import com.huilian.iotbox.data.po.User;
import com.huilian.iotbox.data.enums.MoneyTypeEnum;
import com.huilian.iotbox.data.service.ErrorLogCommonService;
import com.huilian.iotbox.data.service.UserBalanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 谢洛涛
 * @date 2021/4/10 9:14
 */
@Service
public class UserBalanceServiceImpl implements UserBalanceService {
    /**
     * 所有修改用户余额的方法都用这里的方法
     **/
    @Autowired
    private ErrorLogCommonService errorLogCommonService;
    @Resource
    private UserCommonDao userCommonDao;

    @Override
    public User subtractBalance(UserDto userDto, int i) {
        User tempUser = userCommonDao.findUserById(userDto.getId());
        if(MoneyTypeEnum.BALANCE.getCode().equals(userDto.getMoneyType())){
            tempUser.setBalance(tempUser.getBalance().subtract(userDto.getSubtractMoney()));
        }else{
            tempUser.setCommissionBalance(tempUser.getCommissionBalance().subtract(userDto.getSubtractMoney()));
        }
        int flag = userCommonDao.updateBalance(tempUser);
        if (flag <= 0) {
            if (i > 3) {
                //插入异常
                errorLogCommonService.writerInfoErrorLog("提现扣除用户余额失败", tempUser);
            } else {
                i++;
                this.subtractBalance(userDto, i);
            }
        }
        return tempUser;
    }

    @Override
    public User addBalance(UserDto userDto, int i) throws Exception{
        // 余额在调用进来前计算好
        User tempUser = userCommonDao.findUserById(userDto.getId());
        String errorMsg = "";
        if(MoneyTypeEnum.BALANCE.getCode().equals(userDto.getMoneyType())){
            tempUser.setBalance(tempUser.getBalance().add(userDto.getAddMoney()));
            errorMsg = "用户加余额失败";
        }else if(MoneyTypeEnum.COMMISSION_BALANCE.getCode().equals(userDto.getMoneyType())){
            tempUser.setCommissionBalance(tempUser.getCommissionBalance().add(userDto.getAddMoney()));
            errorMsg = "用户加分润余额失败";
        }

        int flag = userCommonDao.updateBalance(tempUser);
        if (flag <= 0) {
            if (i > 3) {
                //插入异常
                errorLogCommonService.writerInfoErrorLog(errorMsg, tempUser);
                throw new Exception(errorMsg);
            } else {
                i++;
                return this.addBalance(userDto, i);
            }
        }
        return tempUser;
    }
}
